﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using CRM.Entity;

using CRM.BLL;
using DP.Web.UI.Controls;
using DP.Web.UI;
using DP.Common;

namespace CRM.Web.PermissionManage
{
    public partial class RolePermissionManage : Common.PageBase
    {
        T_PERMISSION_BLL bll = new T_PERMISSION_BLL();
        T_ROLE_BLL rBll = new T_ROLE_BLL();
        T_ROLEPERMISSION_BLL rpBll = new T_ROLEPERMISSION_BLL();

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlROLEIDBinding();

                tvPermissionBinding();
            }
        }


        #region 页面初始化数据绑定



        /// <summary>
        /// DDLs the ROLEID binding.
        /// </summary>
        private void ddlROLEIDBinding()
        {
            StringBuilder sql = new StringBuilder();
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");
            }
            ddlROLEID.DataSource = rBll.GetList(sql.ToString());
            ddlROLEID.DataTextField = "RoleName";
            ddlROLEID.DataValueField = "RoleID";
            ddlROLEID.DataBind();
        }


     




        #endregion


        /// <summary>
        /// Tvs the permission binding.
        /// </summary>
        private void tvPermissionBinding()
        {
            tvPermission.Nodes.Clear();
            List<T_PERMISSION_Entity> list = bll.GetList(" ");
            List<T_ROLEPERMISSION_Entity> rolepermissionList = rpBll.GetList(string.Format(" and ROLEID = {0} ", ddlROLEID.SelectedValue.Trim()));

            TreeNode node = new TreeNode();
            node.Text = "操作";
            tvPermissionRecursiveBinding(list, rolepermissionList, node);
            tvPermission.Nodes.Add(node);
            tvPermission.ExpandAll();
        }

        /// <summary>
        /// Tvs the permission recursive binding.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="rolepermissionList">The rolepermission list.</param>
        /// <param name="parentNode">The parent node.</param>
        private void tvPermissionRecursiveBinding(List<T_PERMISSION_Entity> list, List<T_ROLEPERMISSION_Entity> rolepermissionList, TreeNode parentNode)
        {
            foreach (var permissionEntity in EnumHelper.EnumToDictionary(typeof(PermissionType)))
            {
                TreeNode pNode = new TreeNode();
                pNode.Value = permissionEntity.Key.ToString();
                pNode.Text = permissionEntity.Value.Trim();
                pNode.ToolTip = "-1";
                var subList = list.FindAll(p =>
                                               {
                                                   if (p.TYPE.Trim() == permissionEntity.Key.ToString())
                                                       return true;
                                                   else 
                                                       return false;
                                               });
                foreach (var entity in subList)
                {
                    TreeNode node = new TreeNode();
                    node.Value = entity.PERMISSIONID.ToString();
                    node.Text = string.Format("{0} ({1}--{2}) {3} ", entity.PERMISSIONNAME, entity.PAGECLASSNAME, entity.PERMISSIONCODE, entity.REMARK.Replace("\r", "").Replace("\n","").Replace("<br />",""));
                    node.Checked = rolepermissionList.Exists(p =>
                                                                 {
                                                                     if (p.PERMISSIONID.ToString() == entity.PERMISSIONID.ToString())
                                                                         return true;
                                                                     else
                                                                         return false;
                                                                 });
                    pNode.ChildNodes.Add(node);
                }
                parentNode.ChildNodes.Add(pNode);
            }
            



        }

        protected void ddlROLEID_SelectedIndexChanged(object sender, EventArgs e)
        {
            tvPermissionBinding();
        }


        /// <summary>
        /// Gets the selected.
        /// </summary>
        /// <param name="nodes">The nodes.</param>
        /// <param name="list">The list.</param>
        private void getSelected(TreeNodeCollection nodes, ref List<T_ROLEPERMISSION_Entity> list)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Checked && (node.ToolTip.Trim() != "-1"))
                {
                    T_ROLEPERMISSION_Entity entity = new T_ROLEPERMISSION_Entity();
                    entity.PERMISSIONID = StringHelper.ToInt(node.Value.ToString(), 0);
                    entity.ROLEID = StringHelper.ToInt(ddlROLEID.SelectedValue.Trim(), 0);
                    list.Add(entity);
                }
                getSelected(node.ChildNodes, ref list);
            }
        }

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            List<T_ROLEPERMISSION_Entity> list = new List<T_ROLEPERMISSION_Entity>();
            getSelected(tvPermission.Nodes, ref list);
            try
            {
                rpBll.Delete("RoleID", ddlROLEID.SelectedValue.Trim());

                foreach (var entity in list)
                {
                    rpBll.Insert(entity);
                }
                PageHelper.ShowMessage(this.Page, "操做权限设置成功！");
            }
            catch (Exception ex)
            {
                PageHelper.ShowMessage(this.Page, "操做权限设置失败！");
            }
        }



    }
}
